package com.flex.core.web.interceptor;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.flex.constants.ErrorConstants;
import com.flex.constants.SystemConstants;
import com.flex.core.model.JsonResponse;
import com.flex.core.utils.JsonUtils;
import com.flex.core.utils.StringUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * 校验并转换json数据为action中的map
 * @author radio
 *
 */
public class JsonInterceptor implements Interceptor{

	private static final long serialVersionUID = -888330055812563006L;

	public void destroy() {
		
	}

	public void init() {
		
	}

	/**
	 * 接受前台传递来的json数据，对数据的有效性进行验证，然后将json数据转换成map格式的数据传给action
	 */
	public String intercept(ActionInvocation ai) throws Exception {
		ActionContext ac = ai.getInvocationContext();
		HttpServletRequest request = (HttpServletRequest) ac
				.get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ac
		.get(ServletActionContext.HTTP_RESPONSE);
		Map<String, Object> map = ac.getParameters();
		String params = request.getParameter(SystemConstants.JSON_PARAM_NAME);
		JsonResponse res = new JsonResponse();
		if(params == null || params.equals("")){
			res.setErrorInfo(-2, ErrorConstants.ERROR_MAP.get(-2));
		}else{
			Map<String, Object> paramMap = new HashMap<String, Object>();
			JsonUtils.getObjFromJson(params, paramMap);
			if(validateKey((String)paramMap.get(SystemConstants.JSON_AUTH_KEY))){
				map.put("paramMap", paramMap);
				return ai.invoke();
			}else{
				res.setErrorInfo(-1, ErrorConstants.ERROR_MAP.get(-1));
			}
		}
		PrintWriter out = response.getWriter();
		out.print(JsonUtils.buildJsonStr(res));
		out.close();
		return null;
	}
	
	/**
	 * 对接受到的json包进行认证
	 * @return
	 */
	private boolean validateKey(String authKey){
		boolean flag = false;
		Date now = new Date();
		String time = String.valueOf(now.getTime());
		StringBuffer sb = new StringBuffer();
		sb.append("#").append("dsgs").append("$").append(time.substring(0, 4));
		String key = StringUtils.md5(sb.toString());
		if(authKey.equals(key)){
			flag = true;
		}
		return flag;
	}

}
